<template>
    <div class="container" style="background-color: #fff;">
        <el-cascader
            style="margin-left: 10px"
            v-model="selectParmas"
            :options="options"
            :props="props"
            @change="handleChange"
            placeholder="选择网关-模块-传感器类型"
            :loading="isLoading"
            clearable
            filterable
            :show-all-levels="true"
            size="default"
            :disabled="options.length === 0"
        />
        <el-date-picker
            v-model="dateTimeRange"
            type="datetimerange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
            style="margin-left: 10px;"
            :shortcuts="shortcuts"
        />
        <el-button type="primary" @click="fetchAndRenderChart" style="margin-left: 10px;">查询</el-button>
        <main>
            <div class="anayleEchart" ref="anayleRef"></div>
        </main>
    </div>
</template>

<script lang="ts" setup>
    /**分析的可视化 */
    import * as echarts from 'echarts'
    import { ECharts } from "echarts"
    import { Adminanayle } from '../../utils/chart'
    import tool from '../../utils/tool'
    import { ref,onMounted,getCurrentInstance, reactive, watch, onActivated } from 'vue'
    import { gatewayStore } from '../../store/gateway'
    import { channelNameDb } from '../../local/channelNameDb'
    import { storeToRefs } from 'pinia'
    import { decompress } from 'compress-json'
    const { proxy }: any = getCurrentInstance()
    
    // 使用网关store
    const gateway_store = gatewayStore()
    const { gatewayList } = storeToRefs(gateway_store)
    
    // 选中的参数 [网关ID, 模块ID, 传感器类型]
    const selectParmas = ref([] as any)
    const props = {
        expandTrigger: 'click' as const, // 改为click触发，更容易选中
        value: 'value',
        label: 'label',
        children: 'children',
        leaf: 'leaf', // 添加leaf属性标识
        checkStrictly: false // 只能选择叶子节点
    }
    const handleChange = (value: any) => {
        console.log('级联选择器值变化:', value)
        console.log('值的类型:', typeof value)
        console.log('值的长度:', value ? value.length : 'null')
        selectParmas.value = value
        
        // 如果选中了完整的三级选项，显示成功消息
        if (value && value.length === 3) {
            console.log('选中完整的三级选项:', {
                gateway: value[0],
                module: value[1], 
                sensor: value[2]
            })
        }
    }
    
    // 级联选中模块到
    let options = ref([] as any)
    let isLoading = ref(false)
    let moduleNum = ref(0)
    let debugMode = ref(false) // 开发时可以设置为true查看调试信息
    
    // 设备名称映射
    const deviceNameMap = ref<Map<string, string>>(new Map())

    const shortcuts = [
        {
            text: '最近一天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近两天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 1);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近三天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 2);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近四天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 3);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近五天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 4);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近六天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 5);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
        {
            text: '最近七天',
            value: () => {
                const end = new Date();
                end.setHours(23, 59, 59, 999);
                const start = new Date();
                start.setDate(end.getDate() - 6);
                start.setHours(0, 0, 0, 0);
                return [start, end];
            },
        },
    ]

    // 日期时间范围
    const dateTimeRange = ref<[Date, Date]>()
    
    // 获取设备名称
    const getDeviceName = (gatewayIp: string, moduleId: number) => {
        // 防止参数为空或未定义
        if (!gatewayIp || !moduleId) {
            return `监测点${moduleId || 'unknown'}`
        }
        
        const key = `${gatewayIp}-${moduleId}`
        const customName = deviceNameMap.value.get(key)
        
        // 返回自定义名称或默认名称
        return customName || `监测点${moduleId}`
    }
    
    // 加载设备名称映射
    const loadDeviceNames = async () => {
        try {
            const nameMap = await channelNameDb.getAllNames()
            deviceNameMap.value = nameMap
        } catch (error) {
            console.error('加载设备名称失败:', error)
        }
    }
    
    // 构建级联选择器选项
    const buildCascaderOptions = async () => {
        console.log('开始构建级联选择器选项')
        console.log('网关列表:', gatewayList.value)
        console.log('模块数量:', moduleNum.value)
        
        if (!gatewayList.value || gatewayList.value.length === 0) {
            console.warn('网关列表为空')
            options.value = []
            return
        }
        
        if (moduleNum.value <= 0) {
            console.warn('模块数量为0')
            options.value = []
            return
        }
        
        // 确保设备名称映射已加载
        if (deviceNameMap.value.size === 0) {
            await loadDeviceNames()
        }
        
        // 构建三级级联结构：网关 -> 模块 -> 传感器类型
        const newOptions = gatewayList.value.map(gateway => ({
            value: gateway.id,
            label: `${gateway.name || '网关' + gateway.id} (${gateway.ip})`,
            children: Array.from({length: moduleNum.value}, (_, i) => ({
                value: i + 1,
                label: getDeviceName(gateway.ip, i + 1), // 使用自定义设备名称
                children: [{
                    value: "uvc",
                    label: "紫外",
                    leaf: true // 标记为叶子节点
                },{
                    value: "inf",
                    label: "红外",
                    leaf: true
                },{
                    value: "tem",
                    label: "温度",
                    leaf: true
                },{
                    value: "hum",
                    label: "湿度",
                    leaf: true
                },{
                    value: "pre",
                    label: "压力",
                    leaf: true
                }]
            }))
        }))
        
        options.value = newOptions
        console.log('构建完成的级联选项:', options.value)
    }
    
    // 监听网关列表变化
    watch(gatewayList, async (newVal) => {
        console.log('网关列表变化:', newVal)
        if (newVal && newVal.length > 0 && moduleNum.value > 0) {
            await buildCascaderOptions()
        }
    }, { deep: true, immediate: true })
    
    // 监听设备名称映射变化
    watch(deviceNameMap, async () => {
        if (gatewayList.value && gatewayList.value.length > 0 && moduleNum.value > 0) {
            await buildCascaderOptions()
        }
    }, { deep: true })
    
    onMounted(async () => {
        try {
            isLoading.value = true
            console.log('开始加载数据')
            
            // 加载设备名称映射
            await loadDeviceNames()
            
            moduleNum.value = 10 // 默认10个模块
            console.log('模块数量:', moduleNum.value)
            
            // 等待网关列表加载后构建级联选择器选项
            if (gatewayList.value && gatewayList.value.length > 0) {
                await buildCascaderOptions()
            }

        } catch (error) {
            console.error('数据加载失败:', error)
            proxy?.notifyError('数据加载失败，请刷新页面重试')
        } finally {
            isLoading.value = false
        }
        
        initEchart()

        // 响应式改变大小
        window.onresize = () => {
            setTimeout(() => {
                if (anayleEchart) {
                    anayleEchart.resize()
                }
            }, 300);
        }
    })

    onActivated(async () => {
        // 清空选择器
        selectParmas.value = [];
        dateTimeRange.value = undefined;
        // 重新显示演示图表
        showDemoChart();
        
        // 重新构建级联选项（以防数据更新）
        if (gatewayList.value && gatewayList.value.length > 0 && moduleNum.value > 0) {
            await buildCascaderOptions()
        }
        
        setTimeout(() => {
            if (anayleEchart) {
                anayleEchart.resize()
            }
        }, 200);
    })


    let anayleRef = ref<HTMLElement>()
    let anayleEchart:ECharts

    const showDemoChart = () => {
        const option = {
            title: {
                text: '演示数据曲线',
                left: 'center',
                textStyle: {
                    color: '#333',
                    fontWeight: 'bold',
                    fontSize: 18
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                data: ['演示数据'],
                top: 'bottom',
                textStyle: {
                    color: '#666'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '10%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00'],
                axisLine: {
                    lineStyle: {
                        color: '#ccc'
                    }
                },
                axisLabel: {
                    color: '#666'
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} °C',
                    color: '#666'
                },
                axisLine: {
                    lineStyle: {
                        color: '#ccc'
                    }
                },
                splitLine: {
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            },
            series: [
                {
                    name: '演示数据',
                    type: 'line',
                    smooth: true,
                    data: [15, 16, 19, 22, 25, 28, 26, 23, 20],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#188df0' },
                            { offset: 1, color: '#188df0' }
                        ])
                    },
                    lineStyle: {
                        width: 3,
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#188df0' },
                            { offset: 1, color: '#188df0' }
                        ])
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(131, 191, 246, 0.5)' },
                            { offset: 1, color: 'rgba(24, 141, 240, 0)' }
                        ])
                    }
                }
            ]
        };
        if (anayleEchart) {
            anayleEchart.setOption(option, true);
        }
    }

    const initEchart = () => {
        anayleEchart = echarts.init(anayleRef.value as HTMLElement)
        showDemoChart()
    }

    const fetchAndRenderChart = async () => {
        if (!selectParmas.value.length) return proxy.$message.error("请选择要分析的网关-模块-传感器类型");
        if (!dateTimeRange.value) return proxy.$message.error("请选择时间范围");
        let [gateway_id, module_id, type] = selectParmas.value;
        let [startTime, endTime] = dateTimeRange.value;

        try {
                const { data: res } = await proxy.$newAdminHttp.get("/admin/getAnayleRecord", {
                params: {
                    gateway_ip: gatewayList.value.find(g => g.id === gateway_id)?.ip,
                    module_id,
                    module_type: type,
                    startTime: tool.tool.formatDate(startTime),
                    endTime: tool.tool.formatDate(endTime)
                }
            });

            if (res.code === 200) {
                const data = decompress(res.data) as any[];                
                if (data.length === 0) {
                    anayleEchart.setOption({
                        title: {
                            text: '该时间段内无数据',
                            left: 'center',
                            top: 'center',
                            textStyle: {
                                color: '#999'
                            }
                        },
                        series: []
                    }, true);
                    return;
                }
                let xData:number[] = data.map((item:any) => item[type])
                // y轴的曲线
                let yData:Array<Array<number>> = data.map((item:any,index:number) => [index,item[type]])
                let timeData:string[] = data.map((item:any) => item.timer)    
                console.log(selectParmas.value)    
                console.log(deviceNameMap.value)
                const currentGateway = gatewayList.value.find(g => g.id === selectParmas.value[0]);
                const currentIp:string | undefined = currentGateway?.ip;
                const gatewayName = currentIp ? currentGateway?.name : '';    
                const devicename = getDeviceName(currentIp || '', selectParmas.value[1]) // 使用getDeviceName函数保证有默认值

                const option = Adminanayle(timeData, selectParmas.value, xData, yData,'',gatewayName,devicename);

                anayleEchart.showLoading('default', { text: '数据量较大，正在加载...' });
                anayleEchart.setOption(option, true);
                anayleEchart.hideLoading();
            } else {
                proxy.$message.error(res.message || '数据获取失败');
            }
        } catch (error) {
            console.error('图表渲染失败:', error);
            proxy.$message.error('图表渲染失败');
        }
    };
</script>

<script lang="ts">
    export default {
        name: "Analysis"
    }
</script>
<style scoped lang="less">
    .container {
        padding: 20px;
        height: calc(100% - 10px);
        .el-select {
            width: 280px;
        }
        main {
            margin-top: 20px;
            height: calc(100% - 60px);
            .anayleEchart  {
                height: 100%;
            }
        }
    }
</style>